package runnable;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

import data.TimerJob;

import utils.Msg;
import utils.SSHUtils;
import utils.Utils;
import jsonobj.JobInfo;
import jsonobj.Message;

public class SubmitJob implements Runnable, Msg {
	JobInfo ji;

	public SubmitJob(JobInfo j) {
		this.ji = j;
	}

	public void run() {
		Process child;
		try {
			TimerJob tj = new TimerJob(ji.jname, ji.nodes, ji.procs,
					Utils.ConvertWalltime(ji.walltime));
			String filename = ji.filedir;
			String path = ji.jname + "/" + filename;
			Runtime run = Runtime.getRuntime();
			if (filename.endsWith(".zip")) {
				Utils.out("+ downloading file " + path);
				if (!new File(path).exists()) {

					if (!SSHUtils.ScpFrom(path)) {
						Utils.out("FAILED RETREIVNG FILE " + filename);
						Utils.ws.send(new Message(JOB_FAILED, ji.jname));
						return;
					}
				}
				run.exec("tar -xf " + path);
			} else {
				Utils.out("+ creating dir " + ji.jname);
				child = run.exec("mkdir " + ji.jname);
				child.waitFor();
				Utils.out("+ downloading file " + path);
				if (!new File(path).exists()) {

					if (!SSHUtils.ScpFrom(path)) {
						Utils.out("FAILED RETREIVNG FILE " + filename);
						Utils.ws.send(new Message(JOB_FAILED, ji.jname));
						return;
					}
				}
			}
			Utils.out("+ creating PBS file");
			child = run.exec("chmod 700 ./" + path);
			child.waitFor();

			child = run.exec("rm ./" + ji.jname + "/" + ji.jname + ".out");
			child.waitFor();

			Utils.createPBSfile(ji);
			Utils.out("+ submitting job");
			child = run.exec("qsub ./" + ji.jname + "/" + "PBS" + ji.jname);
			tj.start();
			child.waitFor();
			Utils.out("+ starting job monitor thread");
			Utils.exec.execute(new JobMonitor(ji, tj));

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
